//
//  NewsDetailPicCell.m
//  OneCard
//
//  Created by sally on 16/2/25.
//  Copyright © 2016年 koalac. All rights reserved.
//

#import "ChatManager.h"
#import "DateUtil.h"
#import "NewsDetailPicCell.h"
#import "ShapedImageView.h"

@interface NewsDetailPicCell ()

@property (weak, nonatomic) IBOutlet UIButton *timeBtn;
@property (weak, nonatomic) IBOutlet UIImageView *headImage;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *headLeftConstraint;
@property (weak, nonatomic) IBOutlet UIView *picView;
@property (weak, nonatomic) IBOutlet UIImageView *picImage;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *picViewHeightLyt;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *picViewWidthLyt;

@end

static CGFloat height = 0;

@implementation NewsDetailPicCell

- (void)awakeFromNib {
  [self initControl];
}

+ (CGFloat)cellHeight {
  return height;
}

- (void)initControl {
  self.headImage.layer.cornerRadius = self.headImage.height / 2;
  self.headImage.layer.masksToBounds = YES;
  self.headImage.userInteractionEnabled = YES;
}

- (void)setCellData:(MessageModel *)cellData {
  _cellData = cellData;

  //头像
  [self.headImage sd_setImageWithURL:[NSURL URLWithString:self.cellData.model.avatar] placeholderImage:[UIImage imageNamed:@"ic_default"]];

  //时间
  NSString *time = [DateUtil getFormatPubTime:self.cellData.model.dateline];
  [self.timeBtn setTitle:time forState:UIControlStateNormal];

  //区分对话双方
  NSString *imageStr;
  CGFloat headLeftWidth = GNormalMargin;
  if (self.cellData.sender == MessageFrom_Mine) {
    imageStr = @"chat_mine_bg.png";
    headLeftWidth = ScreenWidth - GNormalMargin - GHeadImageHeight;
  } else if (self.cellData.sender == MessageFrom_Other) {
    imageStr = @"chat_other_bg.png";
    headLeftWidth = GNormalMargin;
  }

  if (imageStr) {
    //设置图片：打磨并匹配尺寸
    UIImage *contentImage = [UIImage imageNamed:@"chat_pic_test"];
    [self setShapePicView:contentImage maskImage:imageStr size:contentImage.size];

    self.headLeftConstraint.constant = headLeftWidth;
    [self updateMessageContentConstraint];
    //立即触发约束更新，自动更新布局
    [self.contentView updateConstraintsIfNeeded];
  }
}


- (void)setCellMsgData:(EMMessage *)message {
  _cellMsgData = message;
    
  //时间
  NSString *time = [DateUtil getFormatTime:self.cellMsgData.timestamp];
  [self.timeBtn setTitle:time forState:UIControlStateNormal];
  
  //区分对话双方
  NSString *imageStr;
  CGFloat headLeftWidth = GNormalMargin;
  EMImageMessageBody *body = self.cellMsgData.messageBodies[0];
  if ([self.cellMsgData.from isEqualToString:self.cellMsgData.conversationChatter]) { //发送者是对方
    imageStr = @"large_image_default";
    headLeftWidth = GNormalMargin;
    
    [self.picImage sd_setImageWithURL:[NSURL URLWithString:body.thumbnailRemotePath] placeholderImage:[UIImage imageNamed:@"ic_default.png"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
      [self setShapePicView:image maskImage:imageStr size:body.thumbnailSize];
    }];
    
    //数据库设置头像
    ChatExtDB *extDb = [ChatExtDB queryExtByUserName:message.conversationChatter];
    NSString *otherAvatar = extDb.avatar;
    [self.headImage sd_setImageWithURL:[NSURL URLWithString:otherAvatar] placeholderImage:[UIImage imageNamed:@"ic_default"]];
  } else {
    imageStr = @"large_image_default";
    headLeftWidth = ScreenWidth - GNormalMargin - GHeadImageHeight;
    self.picImage.image = [UIImage imageWithContentsOfFile:body.thumbnailLocalPath];
    
    //本地缓存设置头像
    UserModel *mineModel = [[CacheManager shareInstance] getLastLoginAccount];
    [self.headImage sd_setImageWithURL:[NSURL URLWithString:mineModel.user_data.user_profile_pic] placeholderImage:[UIImage imageNamed:@"ic_default"]];
  }
  
  if (imageStr) {
    //打磨图片
    [self setShapePicView:self.picImage.image maskImage:imageStr size:body.thumbnailSize];
    
    self.headLeftConstraint.constant = headLeftWidth;
    [self updateMessageContentConstraint];
    //立即触发约束更新，自动更新布局
    [self.contentView updateConstraintsIfNeeded];
  }
}


#pragma mark - 私有方法
#pragma mark 打磨图片
- (void)setShapePicView:(UIImage *)contentImage maskImage:(NSString *)imageStr size:(CGSize)size {
  //打磨尺寸
  CGSize markSize = [ChatManager compressSizeWithImageSize:size];

  self.picViewWidthLyt.constant = markSize.width;
  self.picViewHeightLyt.constant = markSize.height;
  height = GNewsDetailPicCellHeight - GNewsDetailPicHeight + markSize.height;
  CGRect markFrame = CGRectMake(0, 0, markSize.width, markSize.height);

  UIImage *maskImage = [UIImage imageNamed:imageStr];
  ShapedImageView *shapedImageView = [[ShapedImageView alloc] initWithFrame:markFrame maskImage:maskImage];
  shapedImageView.image = contentImage;

  //移除子view
  for (id subView in self.picView.subviews) {
    [subView removeFromSuperview];
  }
  [self.picView addSubview:shapedImageView];
}

#pragma mark 调整内容的尺寸位置
- (void)updateMessageContentConstraint {
  CommonMethod *common = [CommonMethod sharedCommonMethod];
  NSLayoutRelation leftRelation = NSLayoutRelationEqual;
  NSLayoutRelation rightRelation = NSLayoutRelationEqual;

  if ([self.cellMsgData.from isEqualToString:self.cellMsgData.conversationChatter]) {//发送者是对方
    leftRelation = NSLayoutRelationEqual;
    rightRelation = NSLayoutRelationGreaterThanOrEqual;
  } else {
    leftRelation = NSLayoutRelationGreaterThanOrEqual;
    rightRelation = NSLayoutRelationEqual;
  }

  NSLayoutConstraint *right = [common findSecondConstraint:self.contentView secondItem:self.picView attribute:NSLayoutAttributeTrailing];
  if (right) {
    //移除
    [self.contentView removeConstraint:right];
  }

  //右约束
  NSLayoutConstraint *addRight = [NSLayoutConstraint constraintWithItem:self.contentView attribute:NSLayoutAttributeTrailing relatedBy:rightRelation toItem:self.picView attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:GChatContentLeftMargin];
  [self.contentView addConstraint:addRight];

  NSLayoutConstraint *left = [common findFirstConstraint:self.contentView firstItem:self.picView attribute:NSLayoutAttributeLeading];
  if (left) {
    //移除
    [self.contentView removeConstraint:left];
  }

  NSLayoutConstraint *addLeft = [NSLayoutConstraint constraintWithItem:self.picView attribute:NSLayoutAttributeLeading relatedBy:leftRelation toItem:self.contentView attribute:NSLayoutAttributeLeading multiplier:1.0 constant:GChatContentLeftMargin];
  [self.contentView addConstraint:addLeft];
}

@end
